package com.xjj.cms.controller;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javacommon.base.BaseRestSpringController;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import org.tln.modules.utils.ServletUtils;


import com.company.project.model.UserInfo;
import com.fins.gt.server.GridServerHandler;
import com.fins.gt.util.ModelUtils;
import com.thoughtworks.xstream.XStream;
import com.xjj.cms.entity.Company;
import com.xjj.cms.service.CompanyService;
import com.xjj.core.modules.orm.Page;

/**
 * @Autowired   @Resource 两种都可以进行注入，但是set 不能注入
 * @author Administrator
 * 
 *Spring mvc Controll的几种中返回ModelAndView

文章分类:Java编程
1.return new ModelAndView("admin/delMsg",model); 
2.return new ModelAndView("redirect:/u/"+currUser.getUserName()); 
3.return new ModelAndView(successView); 
4.return new ModelAndView(successView).addObject("articleList", articleList.getItems()).addObject("channel", channel) 

采用惯例优先原则 

ModelAndView mav=new ModelAndView("admin/delMsg"); 
mav.addObject("user",user), 
mav.addObject("blog",blog), 
return mav; 
 */
@Controller
@RequestMapping("/company")
public class CompanyController  extends BaseRestSpringController<Company,java.lang.Long>{
	
	private static final Logger logger = LoggerFactory.getLogger(CompanyController.class);
	
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null; 
	
	private Company entity;
	
	
	private CompanyService companyManager;
	
	private final String LIST_ACTION = "redirect:/company";
	
	private MockHttpServletRequest request;

	private MockHttpServletResponse response;
	
	private Page<Company> page = new Page<Company>(20);//每页5条记录
	
	@Autowired
	public void setCompanyManager(CompanyService companyManager) {
		this.companyManager = companyManager;
	}



	@Resource
	private AnnotationMethodHandlerAdapter annotationMethodHandlerAdapter;
		
	/** 列表 */
	@Override
	public String index(HttpServletRequest request,HttpServletResponse response,Company company,Model model) {
		/*PageRequest<Map> pageRequest = newPageRequest(request,DEFAULT_SORT_COLUMNS);
		//pageRequest.getFilters(); //add custom filters
		
		Page page = this.companyManager.findByPageRequest(pageRequest);
		
		ModelAndView result = toModelAndView(page, pageRequest);
		result.addObject("company",company);
		result.setViewName("/company/list");
		return result;*/
		//System.out.println("companyManager--- "+companyManager);
		/*logger.info("logger.info-------------- "+companyManager);
		Company company2 = this.companyManager.getCompanyById(12L);
		logger.info("company--- "+company2.getName());
		Company entity = new Company();
		entity.setCompanylevel(3L);
		entity.setName("liangqz");
		entity.setParentid(4L);
		this.companyManager.saveCompany(entity);
		company2.setName("name33333333333333");
		this.companyManager.updateCompany(company2);*/
		//List list = this.companyManager.getAllCompanyList();
		//logger.info("返回页面去--- "+list.size());
		//company = this.companyManager.getCompanyById(3L);
		//logger.info("怎么都不更新？");
		//company.setName("liangdh");
		//this.companyManager.updateCompany(company);
		//logger.info("怎么都不更新？");
		Map map = new HashMap();
		page = this.companyManager.getAllCompanyByHql(map,1,20);
		logger.info("page:  "+page);
		return "/company/list";//new ModelAndView("/company/list","page", page);
	}
	
	@RequestMapping(value="/save")
	public String doSave(HttpServletRequest request,HttpServletResponse response) {
		GridServerHandler gridServerHandler = new GridServerHandler(request,response);
		//取得新增的数据集合, 每条数据记录在 map 里
		//List insertedRecords = gridServerHandler.getInsertedRecords();
		JsonNode insertJsonNode = gridServerHandler.getInsertedJsonNodeRecords();
		Iterator<JsonNode> insertNodes = insertJsonNode.getElements(); 
		
		while (insertNodes.hasNext()) {  
			logger.info("保存操作.............");
			Company entity = new Company();
            JsonNode node = insertNodes.next();
            String name = node.get("name").getTextValue();
            entity.setName(name);
            this.companyManager.saveCompany(entity);
        }
		
		JsonNode updateJsonNode = gridServerHandler.getUpdatedJsonNodeRecords();
		Iterator<JsonNode> updateNodes = updateJsonNode.getElements(); 
		
		while (updateNodes.hasNext()) {  
			logger.info("更新操作.............");
			
			ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally  
            JsonNode node = updateNodes.next();
            try {
				entity = mapper.readValue(node, Company.class);
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
            /*Long id = node.get("id").getLongValue();
            //Company entity = this.companyManager.getCompanyById(id);
            
            String name = node.get("name").getTextValue();
            //entity.setId(id);
            entity.setName(name);
            logger.info("node--- "+name);*/
			//this.companyManager.deleteCompany(24L);
			/*Company company = this.companyManager.getCompanyById(14L);
			company.setName("14name");
			this.companyManager.updateCompany(company);*/
            this.companyManager.saveCompany(entity);
        }
		
		JsonNode deleteJsonNode = gridServerHandler.getDeletedJsonNodeRecords();
		Iterator<JsonNode> deleteNodes = deleteJsonNode.getElements(); 
		
		while (deleteNodes.hasNext()) {  
			logger.info("删除操作.............");
			Company entity = new Company();
            JsonNode node = deleteNodes.next();
            Long id = node.get("id").getLongValue();
            
            this.companyManager.deleteCompany(id);
        }
		
		//设置该次操作是否成功.
		gridServerHandler.setSuccess(true);
		
		//如果操作不成功 你也可以自定义一些异常信息发送给客户端.
		//gridServerHandler.setSuccess(false);
		
		//向客户端输出json字符串.
		renderJson(response,gridServerHandler.getSaveResponseText());
		logger.info("SUCCESS............");
		return null;//new ModelAndView("/company/list");
	}
	
	@Override
	public String list(HttpServletRequest request,HttpServletResponse response,
			Company company,Model model){
		Map map = new HashMap();
		logger.info("***************list********************");
		GridServerHandler gridServerHandler = new GridServerHandler(request,response);
		Map param = gridServerHandler.getParameters() ;
		logger.info("传递参数param---- "+param);
		JsonNode parametersJsonNode = gridServerHandler.getParametersJsonNode();
		logger.info("传递参数param---- "+parametersJsonNode);
		//过滤
		List sortInfoList = gridServerHandler.getSortInfo();
		logger.info("sortInfoList---"+sortInfoList.size());
		List list = gridServerHandler.getFilterInfo();
		logger.info("list--- "+list);
		//获取总记录数
		int pageNo = gridServerHandler.getPageNum();//第几页
		//logger.info("pageNo------------ "+pageNo);
		int pageSize = gridServerHandler.getPageSize();//每页多少条记录
		//logger.info("pageSize------------ "+pageSize);
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page = this.companyManager.getAllCompanyByHql(map,pageNo,pageSize);
		logger.info("page size== "+page.getTotalCount());
		//jsonAwareCollect.add("advertisePosition");
		//page.setResult(result);
		gridServerHandler.setTotalRowNum(page.getTotalCount());
		gridServerHandler.setData(page.getResult());
		//绕过jsp 、freemarker 进行，非常的酷
		renderJson(response, gridServerHandler.getLoadResponseText());
		
		return null;
	}
	
	/** 进入新增 *//*
	@Override
	public String _new(HttpServletRequest request,HttpServletResponse response,@ModelAttribute Company company,Model model) throws Exception {
		model.addAttribute("company", company);
		return "/company/new";
	}*/
	
	/** 显示 */
	@Override
	public String show(@PathVariable java.lang.Long id,Model model) throws Exception {
		Company company = new Company();//(UserInfo)userInfoManager.getById(id);
		company.setId(1L);
		company.setName("liangqz");
		model.addAttribute("company", company);
		return "/company/show";
	}
	
	/** 编辑 */
	@Override
	public String edit(@PathVariable java.lang.Long id,Model model) throws Exception {
		UserInfo userInfo = new UserInfo();//(UserInfo)userInfoManager.getById(id);
		userInfo.setAge(3);
		model.addAttribute("userInfo", userInfo);
		return "/userinfo/edit";
	}
	
	/** 保存新增 */
	@Override
	public String create(HttpServletRequest request,HttpServletResponse response,Company company,Model model) throws Exception {
		//userInfoManager.save(userInfo);
		//return "redirect:/owners/" + ownerId;//重定向
		return LIST_ACTION;
	}
	
	/** 保存更新 */
	@Override
	public String update(@PathVariable java.lang.Long id,Model model,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		UserInfo userInfo = new UserInfo();//(UserInfo)userInfoManager.getById(id);
		bind(request,userInfo);
		//userInfoManager.update(userInfo);
		return LIST_ACTION;
	}
	
	/** 删除 */
	@Override
	//@RequestMapping(method = RequestMethod.DELETE)
	public String delete(@PathVariable java.lang.Long id,Model model) {
		//userInfoManager.removeById(id);
		return LIST_ACTION;
	}

//	/** 批量删除 */
//	@Override
//	public String batchDelete(java.lang.Long[] items,Model model) {
//		for(int i = 0; i < items.length; i++) {
//			//userInfoManager.removeById(items[i]);
//		}
//		return LIST_ACTION;
//	}
	
	@RequestMapping(value="/lqz")
	public String lqz(Model model)throws Exception{
		System.out.println("create..controller...............");
		System.out.println("create {}"+companyManager);
		HashMap<String,Object> hashMap = new HashMap<String,Object>();
		hashMap.put("success", "true");
		model.addAttribute("msg", hashMap);
		return null;
	}
	
	// ,@RequestBody UserInfo userInfo  增加这个就报错
	@RequestMapping(value="{pageNumber}/{pageSize}")
	public String list(@PathVariable("pageNumber") int pageNumber,
			@PathVariable("pageSize") int pageSize,Model model) throws Exception{
		logger.info("----------------------"+pageNumber);
		System.out.println("create..controller...............");
		System.out.println("create {}"+companyManager);
		HashMap<String,Object> hashMap = new HashMap<String,Object>();
		hashMap.put("success", "true");
		model.addAttribute("msg", hashMap);
		return null;
	}
	
   @RequestMapping(value = "test/{id}", method = RequestMethod.GET)
   public String show(@PathVariable("id") Long id, ModelMap modelMap) {
	  System.out.println(id+"Identifier must be provided.");
	  UserInfo userInfo  =  new UserInfo();
	  userInfo.setUserId(1L);
	  userInfo.setAge(2);
	  //userInfo.setBirthDate(new Date(""));
	  userInfo.setUsername("liangqz");
      modelMap.addAttribute("userInfo", new UserInfo());
      return "person/show";
   }
  

	
	
	protected void jsonPostInit() {
		addJsonHeader();
		request.setMethod(RequestMethod.POST.toString());
	}

	protected void jsonGetInit() {
		addJsonHeader();
		request.setMethod(RequestMethod.GET.toString());
	}

	protected void jsonPutInit() {
		addJsonHeader();
		request.setMethod(RequestMethod.PUT.toString());
	}

	protected String toJson(Object o) throws Exception {
		System.out.println("toJson...............");
		StringWriter sw = new StringWriter();
		ObjectMapper mapper = new ObjectMapper();
		System.out.println("toJson......start.........");
		mapper.writeValue(sw, o);
		System.out.println("toJson.......end......");
		System.out.println("sw--- "+sw.toString());
		return sw.toString();
	}
	
	protected String toXml(Object o)throws Exception{
		XStream xstream = new XStream();
		xstream.autodetectAnnotations(true);
		return xstream.toXML(o);
	}

	private void addJsonHeader() {
		init();
		request.addHeader("Accept", "application/json, text/javascript, */*");
		request.addHeader("Content-Type", "application/json; charset=UTF-8");
	}


	private void addXmlHeader() {
		init();
		request.addHeader("Accept", "application/xml, text/xml, */*");
		request.addHeader("Content-Type", "application/xml; charset=UTF-8");
	}

	private void init() {
		request = new MockHttpServletRequest();
		request.setCharacterEncoding("UTF-8");
		response = new MockHttpServletResponse();
	}
	
	protected void xmlGetInit() {
		addXmlHeader();
		request.setMethod(RequestMethod.GET.toString());
	}

	protected void xmlPostInit() {
		addXmlHeader();
		request.setMethod(RequestMethod.POST.toString());
	}

	protected void xmlPutInit() {
		addXmlHeader();
		request.setMethod(RequestMethod.PUT.toString());
	}
	
	
	
	private static ObjectMapper mapper = new ObjectMapper();
	
	//-- header 常量定义 --//
    private static final String HEADER_ENCODING = "encoding";
    private static final String HEADER_NOCACHE = "no-cache";
    private static final String DEFAULT_ENCODING = "UTF-8";
    private static final boolean DEFAULT_NOCACHE = true;
	
	
	//-- 绕过jsp/freemaker直接输出文本的函数 --//
    /**
     * 直接输出内容的简便函数.

     * eg.
     * render("text/plain", "hello", "encoding:GBK");
     * render("text/plain", "hello", "no-cache:false");
     * render("text/plain", "hello", "encoding:GBK", "no-cache:false");
     *
     * @param headers 可变的header数组，目前接受的值为"encoding:"或"no-cache:",默认值分别为UTF-8和true.
     */
    public static void render(HttpServletResponse response, final String contentType, final String content, final String... headers) {
            response = initResponseHeader(response,contentType, headers);
            try {
                    response.getWriter().write(content);
                    response.getWriter().flush();
            } catch (IOException e) {
                    throw new RuntimeException(e.getMessage(), e);
            }
    }

    /**
     * 直接输出文本.
     * @see #render(String, String, String...)
     */
    public static void renderText(HttpServletResponse response, final String text, final String... headers) {
            render(response, ServletUtils.TEXT_TYPE, text, headers);
    }

    /**
     * 直接输出HTML.
     * @see #render(String, String, String...)
     */
    public static void renderHtml(HttpServletResponse response, final String html, final String... headers) {
            render(response, ServletUtils.HTML_TYPE, html, headers);
    }

    /**
     * 直接输出XML.
     * @see #render(String, String, String...)
     */
    public static void renderXml(HttpServletResponse response, final String xml, final String... headers) {
            render(response, ServletUtils.XML_TYPE, xml, headers);
    }

    /**
     * 直接输出JSON.
     *
     * @param jsonString json字符串.
     * @see #render(String, String, String...)
     */
    public static void renderJson(HttpServletResponse response, final String jsonString, final String... headers) {
            render(response,ServletUtils.JSON_TYPE, jsonString, headers);
    }

    /**
     * 直接输出JSON,使用Jackson转换Java对象.
     *
     * @param data 可以是List<POJO>, POJO[], POJO, 也可以Map名值对.
     * @see #render(String, String, String...)
     */
    public static void renderJson(HttpServletResponse response, final Object data, final String... headers) {
            response = initResponseHeader(response, ServletUtils.JSON_TYPE, headers);
            try {
                    mapper.writeValue(response.getWriter(), data);
            } catch (IOException e) {
                    throw new IllegalArgumentException(e);
            }
    }

    /**
     * 直接输出支持跨域Mashup的JSONP.
     *
     * @param callbackName callback函数名.
     * @param object Java对象,可以是List<POJO>, POJO[], POJO ,也可以Map名值对, 将被转化为json字符串.
     */
    public static void renderJsonp(HttpServletResponse response, final String callbackName, final Object object, final String... headers) {
            String jsonString = null;
            try {
                    jsonString = mapper.writeValueAsString(object);
            } catch (IOException e) {
                    throw new IllegalArgumentException(e);
            }

            String result = new StringBuilder().append(callbackName).append("(").append(jsonString).append(");").toString();

            //渲染Content-Type为javascript的返回内容,输出结果为javascript语句, 如callback197("{html:'Hello World!!!'}");
            render(response, ServletUtils.JS_TYPE, result, headers);
    }

    /**
     * 分析并设置contentType与headers.
     */
    private static HttpServletResponse initResponseHeader(HttpServletResponse response, final String contentType, final String... headers) {
            //分析headers参数
            String encoding = DEFAULT_ENCODING;
            boolean noCache = DEFAULT_NOCACHE;
            for (String header : headers) {
                    String headerName = StringUtils.substringBefore(header, ":");
                    String headerValue = StringUtils.substringAfter(header, ":");

                    if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
                            encoding = headerValue;
                    } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
                            noCache = Boolean.parseBoolean(headerValue);
                    } else {
                            throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
                    }
            }

            //HttpServletResponse response = ServletActionContext.getResponse();
            logger.info("response:::   "+response);
            //设置headers参数
            String fullContentType = contentType + ";charset=" + encoding;
            response.setContentType(fullContentType);
            if (noCache) {
                    ServletUtils.setNoCacheHeader(response);
            }

            return response;
    }
    
    
    public Company getEntity() {
		return entity;
	}

	public void setEntity(Company entity) {
		this.entity = entity;
	}
	

	

}
